Telegram Group & Telegram Channel
🎯 Как настроить CORS в Spring Boot

Когда фронт и бэк живут на разных доменах — CORS становится головной болью. Но Spring Boot даёт достаточно способов это настроить — от простых аннотаций до централизованной фильтрации.

1️⃣ Минимальная настройка — через @CrossOrigin

Если нужно открыть доступ только к одному контроллеру или методу:
@CrossOrigin(origins = "https://example.com")
@RestController
public class ApiController {
@GetMapping("/data")
public String getData() {
return "OK";
}
}


Удобно для быстрого прототипа, но неудобно для масштабируемого решения.

2️⃣ Глобальная настройка через WebMvcConfigurer

Если CORS нужен везде, лучше использовать конфигурационный класс:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}


Даёт полный контроль. Можно задать разные правила для разных путей.

3️⃣ Настройка CORS через application.yml (Spring Cloud Gateway)

Если вы используете Gateway, настройка может быть ещё проще:
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "https://example.com"
allowedMethods:
- GET
- POST
allowedHeaders: "*"


Подходит, если CORS должен работать до попадания запроса в конкретный микросервис.

4️⃣ CORS + безопасность

Если CORS работает «через раз», возможно, его блокирует Spring Security. Добавьте .cors() в конфигурацию:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors() // 👈 Без этого CORS не заработает
.and()
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
}


5️⃣ Тестирование CORS

Проверьте через curl:
curl -H "Origin: https://example.com" \
-H "Access-Control-Request-Method: GET" \
-X OPTIONS http://localhost:8080/data -v


Ответ должен содержать заголовки:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET


📌 Не оставляйте allowedOrigins("*") в проде. Это дыра в безопасности. Нужно чётко указывать домены.

💬 Как вы обычно настраиваете CORS в своих микросервисах?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6615
Create:
Last Update:

🎯 Как настроить CORS в Spring Boot

Когда фронт и бэк живут на разных доменах — CORS становится головной болью. Но Spring Boot даёт достаточно способов это настроить — от простых аннотаций до централизованной фильтрации.

1️⃣ Минимальная настройка — через @CrossOrigin

Если нужно открыть доступ только к одному контроллеру или методу:

@CrossOrigin(origins = "https://example.com")
@RestController
public class ApiController {
@GetMapping("/data")
public String getData() {
return "OK";
}
}


Удобно для быстрого прототипа, но неудобно для масштабируемого решения.

2️⃣ Глобальная настройка через WebMvcConfigurer

Если CORS нужен везде, лучше использовать конфигурационный класс:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}


Даёт полный контроль. Можно задать разные правила для разных путей.

3️⃣ Настройка CORS через application.yml (Spring Cloud Gateway)

Если вы используете Gateway, настройка может быть ещё проще:
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "https://example.com"
allowedMethods:
- GET
- POST
allowedHeaders: "*"


Подходит, если CORS должен работать до попадания запроса в конкретный микросервис.

4️⃣ CORS + безопасность

Если CORS работает «через раз», возможно, его блокирует Spring Security. Добавьте .cors() в конфигурацию:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors() // 👈 Без этого CORS не заработает
.and()
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
}


5️⃣ Тестирование CORS

Проверьте через curl:
curl -H "Origin: https://example.com" \
-H "Access-Control-Request-Method: GET" \
-X OPTIONS http://localhost:8080/data -v


Ответ должен содержать заголовки:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET


📌 Не оставляйте allowedOrigins("*") в проде. Это дыра в безопасности. Нужно чётко указывать домены.

💬 Как вы обычно настраиваете CORS в своих микросервисах?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6615

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

Launched in 2013, Telegram allows users to broadcast messages to a following via “channels”, or create public and private groups that are simple for others to access. Users can also send and receive large data files, including text and zip files, directly via the app.The platform said it has more than 500m active users, and topped 1bn downloads in August, according to data from SensorTower.

That strategy is the acquisition of a value-priced company by a growth company. Using the growth company's higher-priced stock for the acquisition can produce outsized revenue and earnings growth. Even better is the use of cash, particularly in a growth period when financial aggressiveness is accepted and even positively viewed.he key public rationale behind this strategy is synergy - the 1+1=3 view. In many cases, synergy does occur and is valuable. However, in other cases, particularly as the strategy gains popularity, it doesn't. Joining two different organizations, workforces and cultures is a challenge. Simply putting two separate organizations together necessarily creates disruptions and conflicts that can undermine both operations.

Библиотека джависта | Java Spring Maven Hibernate from ca


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA